import smtplib,requests
from datetime import datetime
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from common.a_env_PATH import pathConf
from common.b_yamlOperate import YamlRead

getEnvC = YamlRead(pathConf.get_userFilePath("data/a_envData/env.yaml"))

class Robot():
    """消息推送机器人"""
    def __init__(self,wx_key=None):
        self.baseUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?"

        ny_debug = getEnvC.getdata()['ny_debug']
        if ny_debug == 0:
            self.wx_key = getEnvC.getdata()['wx_key'][0]
        else:
            self.wx_key = getEnvC.getdata()['wx_key'][1]
        if wx_key == None:
            self.wx_url = self.baseUrl + self.wx_key
        else:
            self.wx_url = self.baseUrl + wx_key

    def send_message(self, message, person_list=None, mobile_list=None):
        """
        :param message 需要发送的消息
        :param person_list 需@人的姓名
        :param mobile_list  需@人的手机号  ["wangqing","@all"]
        :param wx_url 企业微信接口
        :return:
        """
        if mobile_list == None:
            mobile_list = ["@all"]
        else:
            mobile_list = mobile_list
        data = {
            "msgtype": "text",
            "text": {
                "content": message,
                "mentioned_list": person_list,
                "mentioned_mobile_list": mobile_list

            }
        }
        r = requests.post(url=self.wx_url,
                          json=data)

    def send_report(self):

        data = {'file': open(pathConf.get_reportPath(), 'rb')}
        id_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?%s&type=file' % (self.wx_key)
        response = requests.post(url=id_url, files=data)
        # print(response.text)
        json_res = response.json()
        media_id = json_res['media_id']
        data = {"msgtype": "file",
                "file": {"media_id": media_id}
                }
        result = requests.post(url=self.wx_url, json=data)
        return (result)

    def send_reportLog(self):

        data = {'file': open(pathConf.get_reportLog(), 'rb')}
        id_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?%s&type=file' % (self.wx_key)
        response = requests.post(url=id_url, files=data)
        # print(response.text)
        json_res = response.json()
        media_id = json_res['media_id']
        data = {"msgtype": "file",
                "file": {"media_id": media_id}
                }
        result = requests.post(url=self.wx_url, json=data)
        return (result)

class SendMailHelper():
    def __init__(self,host,port,sender,receivers,password=None):
        self.host = host
        self.port = port
        self.sender = sender
        self.receivers = receivers

        self.password = password
        self.msg = MIMEMultipart('mixed')

        self.timestamp = datetime.now().timestamp()
        self.runtime = str(datetime.now())[0:19]
        self.subject = self.runtime + " " + " 测试报告"
        self.msg['Subject'] = self.subject
        self.msg['From'] = sender
        self.msg['To'] = ','.join(receivers)
        # print(self.msg)

    def add_text(self, text_plain):
        text_plain = MIMEText(text_plain, 'plain', 'utf-8')
        self.msg.attach(text_plain)

    def add_html(self, html):
        text_html = MIMEText(html, 'html', 'utf-8')
        self.msg.attach(text_html)

    def add_img(self, img_name, sendimagefile):
        '''
        发送图片
        调用示例:
            sendimagefile = open(img_path, 'rb').read()
            add_img('ima_name',sendimagefile)
        :param imgname: 图片路径
        :return:
        '''
        img_datas = open(sendimagefile, "rb").read()                        # 读取图片内容
        image = MIMEImage(img_datas)
        image.add_header('Content-ID', '<image1>')
        image["Content-Disposition"] = 'attachment; filename="{}"'.format(img_name)
        self.msg.attach(image)

    def add_file(self,sendfile):
        '''
        发送附件
            调用示例：
                    sendfile = open(r'xxxx.xls', 'rb').read()
                    add_file('file_name',sendfile)
        :param filename: 附件名称。 与原文件名一致，不包含路径. 在 text_att.add_header()中添加 filename
        :param sendfile: 附件文件。 与原文件名一致，包含路径
        :return:
        '''

        # 构造附件
        text_att = MIMEText(open(sendfile, 'rb').read(), 'base64', 'utf-8')
        text_att["Content-Type"] = 'application/octet-stream'
        # 以下附件可以重命名成aaa.txt
        # text_att["Content-Disposition"] = 'attachment; filename="aaa.txt"'
        # 另一种实现方式
        text_att.add_header('Content-Disposition', 'attachment', filename=self.runtime + " " + " 测试报告.html")
        # 以下中文测试不ok
        # text_att["Content-Disposition"] = u'attachment; filename="中文附件.txt"'.decode('utf-8')
        self.msg.attach(text_att)

    def send(self):
        try:
            # print("开始连接")
            smtpobj = smtplib.SMTP_SSL(self.host, self.port)
            smtpobj.login(self.sender,self.password)
            smtpobj.sendmail(self.sender, self.msg['To'].split(','), self.msg.as_string())
            smtpobj.quit()
            smtpobj.close()
        except smtplib.SMTPException as e:
            pass
            # print(e)

SendMail = SendMailHelper("smtp.qq.com",465,"1014371820@qq.com",["1130641623@qq.com","18786644913@139.com","yangchengao@merrige.cn"],"tmdphytysqixbcjc")


if __name__ == "__main__":
    pass
    # S = SendMailHelper("smtp.qq.com",465,"1014371820@qq.com",["1130641623@qq.com","18786644913@139.com,"],"tmdphytysqixbcjc")
    # S.add_text("测试正文111")
    # S.add_img("tttt.png",r"C:\Users\Administrator\Desktop\tttt.png")
    # S.add_file(r"C:\Users\Administrator\Desktop\report.html")
    # S.send()
    # print(S.runtime )

    # Rob = Robot()
    # Rob.post_file()

